// This file is part of SyncStar, free software released under GPL v2.
package com.syncstar;

import android.app.Service;
import android.content.Intent;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

/** Service for noticing that the phone's internal message database has
 * changed, and scheduling a call to populatePresenceTable().
 */
public class UpdateService extends Service {
  private static final String TAG = SyncService.class.getSimpleName();

  ContentObserver contentObserver_;

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e(TAG, "CONNX UpdateService onStartCommand startId=" + startId);
    return START_STICKY;
  }

  @Override
  public void onCreate() {
    Log.e(TAG, "CONNX UpdateService onCreate");
    final String url = "content://sms/";
    final Uri uri = Uri.parse(url);
    contentObserver_ = new SmsContentObserver(new Handler());
    getContentResolver().registerContentObserver(uri, true, contentObserver_);
  }

  @Override
  public void onDestroy() {
    Log.e(TAG, "CONNX UpdateService onDestroy isNull=" +
          (contentObserver_ == null));
    if (contentObserver_ != null) {
      getContentResolver().unregisterContentObserver(contentObserver_);
      contentObserver_ = null;
    }
  }

  class SmsContentObserver extends ContentObserver {
    public SmsContentObserver(Handler handler) {
      super(handler);
    }
    @Override
    public boolean deliverSelfNotifications() {
      return true;
    }
    @Override
    public void onChange(boolean selfChange) {
      // With content://sms/ or content://mms-sms,
      // this gets called when an message is added and when
      // a message is deleted. It doesn't get called when an entire thread is
      // deleted (but that's no problem).
      //
      // With content://mms-sms/conversations it might get called, see
      // http://stackoverflow.com/questions/4288091/android-observing-sms-for-deleted-threads
      // Maybe content://sms/conversations also works?
      //
      // But we don't care we don't need populatePresenceTable() be called upon
      // deletions.
      super.onChange(selfChange);
      PopulateService.populatePresenceTableNowOrLater(UpdateService.this);
    }
  }
}
